import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo } from '@/types/user'
import Logger from '@/utils/logger'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')
  const userDetail = ref<UserInfo | null>(null)
  const userRoleLocal = ref(localStorage.getItem('userRole') || '')

  // 使用计算属性来判断登录状态
  const isLoggedIn = computed(() => !!token.value)

  // 获取用户角色
  const userRole = computed(() => userRoleLocal.value)

  const setUserInfo = (info: { token: string; username: string }) => {
    token.value = info.token
    username.value = info.username
    localStorage.setItem('token', info.token)
    localStorage.setItem('username', info.username)
    Logger.info('用户信息已更新', { username: info.username })
  }

  const updateUserDetails = (info: UserInfo) => {
    userDetail.value = info
    Logger.info('用户详细信息已更新', info)
    localStorage.setItem('userRole', getUserRole(info.role))
  }

  function getUserRole(role?: number) {
    const role_value = role || 4
    switch (role_value) {
      case 1:
        return 'super_admin'
      case 2:
        return 'admin'
      case 3:
        return 'photographer'
      default:
        return 'user'
    }
  }

  const clearUserInfo = () => {
    token.value = ''
    username.value = ''
    userDetail.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('userRole')
    Logger.info('用户信息已清除')
  }

  return {
    token,
    username,
    isLoggedIn, // 导出计算属性
    userDetail,
    userRole,
    setUserInfo,
    getUserRole,
    updateUserDetails,
    clearUserInfo,
  }
})
